from flask import session, request, current_app, abort
from project.apps.home import home_blueprint
from flask_restful import Resource, Api
from project.models.news import Channel, Article
from project.models.user import Relation
from flask import g
from project import db
from project.utils.user import loginrequired


index_api = Api(home_blueprint)

# @home_blueprint.route('/')
# def index():
#
#     session['user_id'] = '123'
#
#     return 'index'


class IndexResource(Resource):

    def get(self):
        """获取首页文章. 根据频道id来获取, 同时能够对数据进行分页处理"""
        # 1.获取参数
        channel_id = request.args.get('channel_id', 1)
        page = request.args.get('page', 1)
        per_page = request.args.get('per_page', 10)

        try:
            page = int(page)
            per_page = int(per_page)
        except Exception:
            page = 1
            per_page = 10

        # 2.根据频道id进行数据查询并分页 [Article]
        page_articles = Article.query.filter(
            Article.channel_id==channel_id
        ).paginate(
            page=page,
            per_page=per_page
        )

        # 3.对文章列表进行转换
        articles_list = []
        for item in page_articles.items:
            articles_list.append({
                'art_id': item.id,
                'title': item.title,
                'aut_id': item.user_id,
                'pubdate': item.ctime.strftime('%Y-%m-%d %H:%M:%S'),
                'aut_name': item.user.name,
                'comm_count': item.comment_count
            })

        return {'results': articles_list, 'per_page': per_page}


class ChannelsResource(Resource):

    def get(self):

        # 1.根据模型查询所有数据[Channel, Channel... ]
        channels = Channel.query.all()
        # 2.将对象列表进行转换
        channels_list = []
        for item in channels:
            channels_list.append({
                'id': item.id,
                'name': item.name
            })
        # 3.返回数据
        return {'channels': channels_list}


class DetailResource(Resource):

    def get(self, article_id):

        # 1.根据id进行数据查询
        article = None
        try:
            article = Article.query.get(article_id)
        except Exception as e:
            current_app.logger.error(e)
            abort(404)

        # 判端是否关注
        is_followed = True

        # 判断是否喜欢
        attitude = 1

        # 判断是否收藏
        is_collected = False

        # 2.将对象转换为字典
        data = {
            "art_id": article.id,
            "title": article.title,
            "pubdate": article.ctime.strftime('%Y-%m-%d %H:%M:%S'),
            "aut_id": article.user.id,
            "aut_name": article.user.name,
            "aut_photo": article.user.profile_photo,
            "content": article.content.content,
            "is_followed": is_followed,
            "attitude": -1,  # 不喜欢0 喜欢1 无态度-1
            "is_collected": is_collected
        }

        # 3.返回响应
        return data


class UserFocusResource(Resource):

    method_decorators = [loginrequired]

    def post(self):

        # 1.接收数据
        user_id = g.user_id
        target_user_id = request.json.get('target')
        # 2.验证数据(省略)
        # 3.数据入库
        re = Relation()
        re.user_id = user_id
        re.target_user_id = target_user_id
        re.relation = Relation.RELATION.FOLLOW

        db.session.add(re)
        db.session.commit()

        # 4.返回响应
        return {'target': target_user_id}


index_api.add_resource(IndexResource, '/')
index_api.add_resource(ChannelsResource, '/channels')
index_api.add_resource(DetailResource, '/articles/<article_id>/')
index_api.add_resource(UserFocusResource, '/user/followings')